import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {HttpService} from '../../services/http.service';
import {UrlAndOPT} from '../../common/url-and-opt.enum';
import {ToastController} from '@ionic/angular';
import {AppConfig} from '../../common/app-config.enum';

@Component({
  selector: 'app-bank-area',
  templateUrl: './bank-area.component.html',
  styleUrls: ['./bank-area.component.scss']
})
export class BankAreaComponent implements OnInit {

  @Input() provinceList: any = []; // 省份列表
  cityList: any[] = null; // 城市列表
  province: any = null; // 所选省份
  city: any = null;
  @Output() closeEmit = new EventEmitter<any>(); // 发送关闭事件

  constructor(
    private toastCtrl: ToastController,
    private service$: HttpService
  ) {
  }

  ngOnInit() {
  }

  // 选择省份后请求相关城市列表
  selectProvince(province: any) {
    // 未选择省份或省份变更
    if (!this.province || (this.province['prov_num'] !== province['prov_num'])) {
      this.province = province;
      this.city = null;
      this.service$.doRequest(UrlAndOPT.auth_bank_area, {provNum: this.province['prov_num']})
        .subscribe(obj => {
          if (obj) {
            this.cityList = obj['obj'];
          }
        });
    }
  }

  // 选择城市
  selectCity(city: any) {
    // 未选择城市或城市变更
    if (!this.city || !(this.city['prov_num'] === city['prov_num'] && this.city['city_num'] === city['city_num'])) {
      this.city = city;
    }
  }

  sureBankArea() {
    if (this.city) {
      this.closeEmit.emit(this.city);
    } else {
      this.showToast('请选择省份和城市');
    }
  }

  closeBankArea() {
    // 发送关闭事件
    this.closeEmit.emit();
  }

  async showToast(txt: string) {
    const toast = await this.toastCtrl.create({
      message: txt,
      position: AppConfig.TOAST_POSITION,
      duration: AppConfig.TOAST_DURATION * 1
    });
    return toast.present();
  }

}
